package utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getTimer;
	
	import interfaces.IAction;
	
	public class CountManager extends EventDispatcher implements IAction
	{
		private var m_target:*;
		private var m_start:Boolean;
		private var m_pause:Boolean;
		private var m_pauseTime:Number;
		
		private var m_startTime:Number;
		private var m_lastTime:Number;
		private var m_count:Number;
		private var m_total:Number;
		private var m_interval:Number;
		
		public function CountManager(mc:*)
		{
			m_count = 0;
			m_total = 0;
			m_target = mc;
			m_start = false;
		}
		
		public function set start(b:Boolean):void
		{
			m_start = b;
			
			if(b)
			{
				m_count = 0;
				m_startTime = getTimer();
				m_lastTime = m_startTime - m_startTime % m_interval;
				dispatchEvent(new Event(Event.CHANGE));
			}else
			{
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		public function get start():Boolean
		{
			return m_start;
		}
		
		public function set pause(b:Boolean):void
		{
			m_pause = b;
			if(b)
			{
				m_pauseTime = getTimer();
			}else
			{
				var time:Number = getTimer() - m_pauseTime;
				m_startTime += time;
				m_lastTime += time;
			}
		}
		
		public function get pause():Boolean
		{
			return m_pause;
		}
		
		public function update(e:Object=null):void
		{
			// 未开始播放
			if(!start || pause)return;	
			
			var temp:Number = getTimer();
			temp -= (temp % m_interval);
			var count:Number = Math.floor((temp - m_lastTime) / m_interval);
			
			// 不足一个间隔
			if(count <= 0)return;
			//
			m_count += count;
			m_lastTime = temp;
			dispatchEvent(new Event(Event.CHANGE));
			// 执行够次数后
			if(m_total == 0)return;
			if(m_count >= m_total) 
			{
				start = false;
				return;
			}
		}
		
		public function get count():Number
		{
			return m_count;
		}
		
		public function set total(n:Number):void
		{
			m_total = n;
		}
		
		public function set interval(n:Number):void
		{
			m_interval = n;
		}
		
		public function get target():*
		{
			return m_target;
		}
	}
}